<?php
	include_once '../models/Model.php';
	session_start();
	$adminId=$_SESSION['userId'];
	$model=new Model();
	$admin=$model->searchUserById($adminId);
	$adminAccName=$admin->getUserAccName();
	$adminName=$admin->getUserName();
	$currentMonth=date('Y-m');
	//echo $month;
	$lastMonth=mktime(0,0,0,date("m",strtotime($currentMonth))-1,date("d",strtotime($currentMonth)),date("Y",strtotime($currentMonth)));
	
	$filename='RVR-'.date('Y-m',$lastMonth).'.csv';
	header("Content-type: application/vnd.ms-excel");
	header("Content-Disposition: csv; filename=".$filename);
	header("Pragma: no-cache");
	header("Expires: 0");
	$hour=date('h')-1;
	echo 'CSY-RVR-GWK52M78'.','.date('Y').','.date('m').','.date('Y',$lastMonth)
	.','.date('m',$lastMonth).','.date('d').','.$hour.','.date('i')
	.','.date('s').','.$adminAccName.','.$adminName."\n";
	$userId=$model->showAllUserId();
	if($userId!=null) 
	{
		foreach($userId as $item)
		{
			//init fee
			$fee=0;
						
			$user=$model->searchUserById($item);
			$userAccName=$user->getUserAccName();
			$userName=$user->getUserName();
			$userEmail=$user->getUserEmail();
			$userTel=$user->getUserTel();
			
			//get unauthorizedtime and generate fine
			$unauthorizedTime=$model->showUserPenalty($item,date('Y-m',$lastMonth));
			//var_dump($unauthorizedTime);
			if($unauthorizedTime!=null)	
				foreach($unauthorizedTime as $time)
					$fee+=100000*ceil($time/30);
		
			//get all order in month
			$order=$model->searchOrderByUserId(date('Y-m',$lastMonth),$item);
					
			if($order!=null)
				foreach ($order as $element)
				{
					$roomId=$element->getRoomId();
					$room=$model->getRoomById($roomId);
					$roomCost=$room->getRoomCost();
			
					//get book time 
					$startTime=$element->getOrderStartTime();
					$endTime=$element->getOrderEndTime();
					$bookTime=(strtotime($endTime)-strtotime($startTime))/60;
					
					//get order status
					$orderStatus=$element->getOrderStatus();
					//booked status
					$orderFee=$model->getOrderFee();
					$cancelFee=$model->getCancelFee();
			
					if($orderStatus==1)
						$fee+=$orderFee;
					//canceled status
					else if($orderStatus==2)
						$fee+=$cancelFee;
					//used status				
					else if($orderStatus==3)
						$fee+=$bookTime/30*$roomCost; 
				}
				echo $userAccName.','.$userName.','.$fee.','.$userEmail.','.$userTel."\n";
		}
	}	
	echo 'END__END__END,'.date('Y',$lastMonth).','.date('m',$lastMonth);
	//header('Location:../view/manager/admin.php');
?>